<template>
  <div class="reset-password">
    <div class="demo-ruleForm login-container" v-if="active==0">
      <h3 class="title">{{$t('m.ForgotPassword')}}</h3>
      <el-form :model="resetForm" ref="resetForm" :rules="formRule">
          <el-form-item :label="$t('m.EmailorPhone')" prop="account">
            <el-input v-model="resetForm.account" auto-complete="off"></el-input>
          </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="warning" style="width:100%;" :loading="loading1" @click="submitResetForm('resetForm')">{{$t('m.Next')}} &gt;
          </el-button>
        </el-form-item>
      </el-form>
      <el-dialog
        :title="$t('m.ResetPassword')"
        :visible.sync="dialogVisible"
        :before-close="goToLogin"
        width="25%">
        <span>{{$t('m.Checkyouremailinbox')}}</span>
        <div class="btootm" style="text-align: center; padding-top: 20px">
          <el-button type="primary" @click="goToLogin">{{$t('m.Close')}}</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="demo-ruleForm login-container" v-else>
      <h3 class="title">{{$t('m.ResetPassword')}}</h3>
      <el-form :model="resetPhoneForm" ref="resetPhoneForm" :rules="rulesResetPhone">
        <el-form-item :label="$t('m.NewPassword')" prop="password">
          <el-input type="password" v-model="resetPhoneForm.password"  auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom:0;" :label="$t('m.Yourphone')">{{resetForm.account}}
          <el-button class="smsBtn" :disabled="sendMsgDisabled" @click="submitSms()">
            <span v-if="sendMsgDisabled">{{$t('m.ResendSMSpasswordtomyphone')}}{{' ' + time+'s'}}</span>
            <span v-else>{{$t('m.SendSMSpasswordtomyphone')}}</span>
          </el-button>
        </el-form-item>
        <el-form-item prop="sms" label="">{{$t('m.Pleasecheckyourphone')}}
          <el-input v-model="resetPhoneForm.sms" :maxlength="4" placeholder="SMS Password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="warning" style="width:100%;" :loading="loading" @click="submitPhoneForm('resetPhoneForm')">{{$t('m.Submit')}}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import {sendSmsUser, resetPassword, forgotEmailPassword} from '@/api/api'
  import Qs from 'qs'
  export default {
    name: 'resetPassword',
    data() {
      return {
        active: 0,//步骤计数
        send: 'Send SMS',
        time: 60, // 发送验证码倒计时
        sendMsgDisabled: false,
        loading: false,
        loading1: false,
        dialogVisible: false,
        resetForm: {
          account: '',
        },
        resetPhoneForm: {
          password: '',
          sms: '',
        },
        formRule: {
          account:[
            {required: true, message: 'Email or Phone is null', trigger: 'blur' }
          ]
        },
        rulesResetPhone: {
          password: [{validator:(rule,value,callback)=>{
              if(/^(?=.*?[0-9]).{8,}$/.test(value) == false){
                callback(new Error("At least 8 or more characters and at least 1 number"));
              }else{
                callback();
              }
            }, trigger:'blur'},
            { required: true, message: 'Please enter password', trigger: 'blur' }
            ],
          sms: [
            {required: true, message: 'sms is null'}
          ]
        }
      }
    },
    methods: {
      timeGo: function () {
        var self = this
        self.sendMsgDisabled = true
        var timeCount = setInterval(function () {
          if ((self.time--) <= 0) {
            self.time = 60
            self.sendMsgDisabled = false
            window.clearInterval(timeCount)
          }
        }, 1000)
      },
      // message alert 用于前端错误提示信息
      messageToastErr (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: 'error'
        })
      },
      // 去掉空格
      trim(str, isGlobal) {
        var result
        result = str.replace(/(^\s+)|(\s+$)/g, '')
        if (isGlobal.toLowerCase() === 'g') {
          result = result.replace(/\s/g, '')
        }
        return result
      },
      // 对用户输入进行验证，邮箱--直接请求后台接口；手机号--显示表单
      submitResetForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(this.resetForm.account)){
              this.submitEmailForm() // 邮箱账号找回密码
            }else{
              this.active++ //手机账号找回密码
            }
          }
        })
      },
      submitSms () {
        if (this.resetPhoneForm.password) {
          let phoneNumber = this.trim(this.resetForm.account, 'g')
          phoneNumber = phoneNumber.substring(1, phoneNumber.length)
          this.timeGo()
          let data = {
            'phoneNumber': phoneNumber,
            'zone': '+95'
          }
          let params = Qs.stringify(data)
          sendSmsUser(params).then( (res) => {
            if (res.data) {
              var data = res.data
              if (data.errorID === 0) {
                console.log(data)
              } else {
                console.log(data.errorID)
                this.showToast(data.errorID)
              }
            }
          })
            .catch((error) => {
              console.log(error)
              this.messageToastErr('error,please try again later')
            })
        } else {
          this.messageToastErr('error submit!!')
          return false
        }
      },
      // 忘记密码 -- 通过手机号重置密码
      submitPhoneForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let phoneNumber = this.trim(this.resetForm.account, 'g')
            // phoneNumber = phoneNumber.substring(1, phoneNumber.length)
            this.timeGo()
            let data = {
              'phone': phoneNumber,
              'zone': '+95',
              'password': this.resetPhoneForm.password,
              'code': this.resetPhoneForm.sms
            }
            let params = Qs.stringify(data)
            this.loading = true
            resetPassword(params).then( (res) => {
              if (res.data) {
                var data = res.data
                if (data.errorID === 0) {
                  console.log(data)
                  this.loading = false
                  this.showToast(data.errorID)
                  this.$router.push('/login')
                } else {
                  console.log(data.errorID)
                  this.showToast(data.errorID)
                  this.loading = false
                }
              }
            })
              .catch((error) => {
                console.log(error)
                this.messageToastErr('error,please try again later')
              })
          } else {
            this.messageToastErr('error submit!!')
            return false
          }
        })
      },
      // 忘记密码 -- 通过邮箱重置密码
      submitEmailForm () {
        let data = {
          'accountEmail': this.resetForm.account,
        }
        let params = Qs.stringify(data)
        this.loading1 = true
        forgotEmailPassword(params)
          .then((res) => {
            if (res.data) {
              var data = res.data
              if (data.errorID === 0) {
                this.showToast(data.errorID)
                this.loading1 = false
                setTimeout(() => {
                  this.dialogVisible = true
                }, 1200)
              } else {
                console.log(data)
                this.loading1 = false
                this.showToast(data.errorID)
              }
            }
          })
          .catch((error) => {
            console.log(error)
            this.loading1 = false
            this.messageToastErr('error,please try again later')
          })
      },
      // 关闭dialog 跳转到login
      goToLogin(){
        this.dialogVisible = false;
        this.$router.push('/login')
      }
    }
  }
</script>

<style >
  .reset-password .login-container{
    border-radius: 5px;
    -moz-border-radius: 5px;
    background-clip: padding-box;
    margin: 0 auto;
    width: 380px;
    padding: 35px 35px 25px 35px;
    background: #fff;
    margin-bottom: 50px;
    box-shadow: none;
    border: none;
  }
  .reset-password .smsBtn {
    width: 100%;
    padding: 12px 5px;
  }
</style>
